<template>
  <div id="map_container">
    <!-- 鼠标位置控件 -->
    <div id="mouse-position"></div>
    <!-- 矢量图和影像图切换 -->
    <div class="map_switch">
      <!-- 矢量图 -->
      <img src="../assets/image/2dimension.png" alt="" @click="toggleTdt_vec" />
      <!-- 影像图 -->
      <img src="../assets/image/3dimension.png" alt="" @click="toggleTdt_img" />
    </div>
    <!-- Popup弹窗 -->
    <div id="popup" class="ol-popup">
      <a href="#" id="popup-closer" class="ol-popup-closer"></a>
      <div id="popup-content"></div>
    </div>
  </div>
</template>

<script>
// import {
//   TiandiMap_vec,
//   TiandiMap_cva,
//   TiandiMap_img,
//   TiandiMap_cia,
//   docLayer,
//   map,
// } from '../map/index'
import { mapState } from 'vuex'

// 视频监控弹窗图层
var drawSource = new ol.source.Vector({
  wrapX: false,
})
var drawLayer = new ol.layer.Vector({
  source: drawSource,
  style: new ol.style.Style({
    image: new ol.style.Icon({
      anchor: [0.8, 150],
      anchorOrigin: 'top-right',
      anchorXUnits: 'fraction',
      anchorYUnits: 'pixels',
      offsetOrigin: 'top-right',
      // offset:[0,10],
      //图标缩放比例
      scale: 0.2,
      //透明度
      opacity: 1,
      //图标的url
      src: '../../src/assets/image/monitor.jpg',
    }),
  }),
})
export default {
  name: 'MapCom',
  components: {},
  data() {
    return {
      // map: null,
      flag: true,
    }
  },
  mounted() {
    this.mapInit()
    this.highLight()
  },
  computed: {
    ...mapState(['highLightCamera', 'map']),
  },
  watch: {
    highLightCamera: function (n, o) {
      if (this.highLightCamera == true) {
        this.highLight()
      } else {
        // console.log('关闭')
        this.map.removeLayer(drawLayer)
      }
    },
    deep: true,
  },
  methods: {
    mapInit() {
      // this.map = map
      // this.map.setTarget('map_container')
      // this.$store.commit('addMap', this.map)

      /* 显示地图 */
      this.TiandiMap_vec = TiandiMap_vec
      this.TiandiMap_cva = TiandiMap_cva
      this.TiandiMap_img = TiandiMap_img
      this.TiandiMap_cia = TiandiMap_cia
      var docName = 'guanggu'
      var docLayer = new Zondy.Map.Doc('', docName, {
        ip: 'localhost',
        port: 6163,
      })
      var map = new ol.Map({
        // 挂载
        target: 'map_container',
        layers: [
          this.TiandiMap_img,
          this.TiandiMap_cia,
          this.TiandiMap_vec,
          this.TiandiMap_cva,
          docLayer,
        ],
        // 显示方式
        view: new ol.View({
          center: [114.38, 30.495],
          projection: 'EPSG:4326',
          zoom: 13,
        }),
      })
      // console.log(map)
      // 将map存储在vuex里
      this.$store.commit('addMap', map)
      this.$store.commit('addLayer', docLayer)

      /*
      实例化视图跳转控件并加载到地图容器中
      */
      var zoomToExtent = new ol.control.ZoomToExtent({
        extent: [114.38, 30.46, 114.4, 30.52],
      })
      map.addControl(zoomToExtent)

      /*
      实例化放大缩小控件并加载到地图容器中
      */
      var zoomslider = new ol.control.ZoomSlider()
      map.addControl(zoomslider)

      /*
      实例化鼠标位置控件（MousePosition）
      */
      var mousePositionControl = new ol.control.MousePosition({
        //坐标格式
        coordinateFormat: ol.coordinate.createStringXY(4),
        //地图投影坐标系（若未设置则输出为默认投影坐标系下的坐标）
        projection: 'EPSG:4326',
        //坐标信息显示样式类名，默认是'ol-mouse-position'
        className: 'custom-mouse-position',
        //显示鼠标位置信息的目标容器
        target: document.getElementById('mouse-position'),
        //未定义坐标的标记
        undefinedHTML: '&nbsp;',
      })
      map.addControl(mousePositionControl)

      /*
      实例化比例尺控件
      */
      var scaleLineControl = new ol.control.ScaleLine({
        //设置比例尺单位，degrees、imperial、us、nautical、metric（度量单位）
        units: 'metric',
      })
      map.addControl(scaleLineControl)

      /*
      实例化鹰眼控件,自定义样式的鹰眼控件
      */
      var overviewMapControl = new ol.control.OverviewMap({
        //鹰眼控件样式（see in overviewmap-custom.html to see the custom CSS used）
        className: 'ol-overviewmap ol-custom-overviewmap',
        //鹰眼中加载同坐标系下不同数据源的图层
        layers: [TiandiMap_img, TiandiMap_cia, TiandiMap_vec, TiandiMap_cva],
        //鹰眼控件展开时功能按钮上的标识（网页的JS的字符编码）
        collapseLabel: '\u00BB',
        //鹰眼控件折叠时功能按钮上的标识（网页的JS的字符编码）
        label: '\u00AB',
        //初始为展开显示方式
        collapsed: false,
        view: new ol.View({
          projection: 'EPSG:4326',
          minZoom: 6,
        }),
      })
      map.addControl(overviewMapControl)
    },

    // 底图开启（矢量图层和矢量注记图层开启）
    toggleTdt_vec() {
      this.TiandiMap_vec.setVisible(true)
      this.TiandiMap_cva.setVisible(true)
    },
    // 底图关闭（矢量图层和矢量注记图层关闭，影像图层和影像注记图层显示）
    toggleTdt_img() {
      this.TiandiMap_vec.setVisible(false)
      this.TiandiMap_cva.setVisible(false)
    },
    // 高亮显示
    highLight() {
      /* 1. 高亮显示所有摄像头点 */
      //创建一个用于查询的点形状
      let pointObj = new Zondy.Object.Point2D(114, 30)
      //设置查询点的搜索半径 (度)
      pointObj.nearDis = 2

      // 查询
      var queryStruct = new Zondy.Service.QueryFeatureStruct()
      //是否包含几何图形信息
      queryStruct.IncludeGeometry = true
      //是否包含属性信息
      queryStruct.IncludeAttribute = true
      //是否包含图形显示参数
      queryStruct.IncludeWebGraphic = false
      //指定查询规则
      var rule = new Zondy.Service.QueryFeatureRule({
        //是否将要素的可见性计算在内
        EnableDisplayCondition: false,
        //是否完全包含
        MustInside: false,
        //是否仅比较要素的外包矩形
        CompareRectOnly: false,
        //是否相交
        Intersect: true,
      })
      //实例化查询参数对象
      var queryParam = new Zondy.Service.QueryParameter({
        geometry: pointObj,
        resultFormat: 'json',
        struct: queryStruct,
        rule: rule,
      })
      var queryService = new Zondy.Service.QueryDocFeature(
        queryParam,
        'guanggu',
        '3',
        {
          ip: 'localhost',
          port: '6163', //访问IGServer的端口号，.net版为6163，Java版为8089
        }
      )

      //执行查询操作，querySuccess为查询回调函数
      queryService.query(querySuccess, queryError)

      //查询失败回调
      function queryError(e) {
        //停止进度条
        // console.log('失败', e)
      }

      // 下面的函数会改变this指向, 所以这里接收一下现在的this, 方便后面使用
      var _this = this
      var new_flag = this.highLightCamera

      //查询成功回调
      function querySuccess(result) {
        // console.log('成功',result);
        if (new_flag) {
          // console.log('显示摄像头成功', result);
          var format = new Zondy.Format.PolygonJSON()
          //将MapGIS要素JSON反序列化为ol.Feature类型数组
          var features = format.read(result)
          drawSource.addFeatures(features)
          _this.map.addLayer(drawLayer)

          _this.map.setView(
            new ol.View({
              projection: 'EPSG:4326',
              center: [114.383, 30.49],
              zoom: 13.2,
            })
          )

          /* 2. 点击显示pop弹窗 */
          // console.log('执行中');
          /* 设置点要素 */
          // 二. 将dom转换成overlay
          var container = document.getElementById('popup')
          var content = document.getElementById('popup-content')
          var closer = document.getElementById('popup-closer')
          const popup = new ol.Overlay({
            //要转换成overlay的HTML元素
            element: container,
            //当前窗口可见
            autoPan: true,
            //Popup放置的位置
            positioning: 'bottom-center',
            //是否应该停止事件传播到地图窗口
            stopEvent: false,
            autoPanAnimation: {
              //当Popup超出地图边界时，为了Popup全部可见，地图移动的速度
              duration: 250,
            },
          })
          _this.map.addOverlay(popup)

          //添加关闭按钮的单击事件（隐藏popup）
          closer.onclick = function () {
            //未定义popup位置
            popup.setPosition(undefined)
            //失去焦点
            closer.blur()
            return false
          }

          /**
           * 动态创建popup的具体内容
           * @param {string} title
           */
          function addFeatrueInfo(info) {
            //新增a元素
            var elementA = document.createElement('a')
            elementA.className = 'class_a'
            elementA.href = '#'
            //elementA.innerText = info.att.title;
            setInnerText(elementA, info.att.title)
            // 新建的div元素添加a子节点
            content.appendChild(elementA)
            //新增p元素
            var elementDiv = document.createElement('p')
            elementDiv.className = 'class_text'
            //elementDiv.innerText = info.att.text;
            setInnerText(elementDiv, info.att.text)
            // 为content添加div子节点
            content.appendChild(elementDiv)
            //新增video元素
            var elementImg = document.createElement('video')
            elementImg.className = 'class_video'
            elementImg.controls = true
            elementImg.src = info.att.videoUrl
            // 为content添加img子节点
            content.appendChild(elementImg)
          }
          /**
           * 动态设置元素文本内容（兼容）
           */
          function setInnerText(element, text) {
            if (typeof element.textContent == 'string') {
              element.textContent = text
            } else {
              element.innerText = text
            }
          }

          // 为map添加点击事件监听，渲染弹出popup
          _this.map.on('click', function (evt) {
            //判断当前单击处是否有要素，捕获到要素时弹出popup
            var feature = _this.map.forEachFeatureAtPixel(
              evt.pixel,
              function (feature, layer) {
                return feature
              }
            )
            if (feature) {
              var obj = feature.values_.values_
              //示例标注点的信息对象
              var featuerInfo = {
                geo: feature,
                att: {
                  //标注信息的标题内容
                  title: '编号：' + obj.编号,
                  //标注详细信息链接
                  titleURL: 'http://www.openlayers.org/',
                  //标注内容简介
                  text: '位置：' + obj.位置,
                  //标注的图片
                  videoUrl: '../src/assets/video/',
                },
              }

              //清空popup的内容容器
              content.innerHTML = ''
              //在popup中加载当前要素的具体信息
              addFeatrueInfo(featuerInfo)
              if (popup.getPosition() == undefined) {
                //设置popup的位置, 此时还未打开过popup弹窗
                var position = feature.getGeometry().getCoordinates()[0]
                popup.setPosition(position)
              } else {
                // 如果feature的为新点击的对象, 则赋予popup新的显示位置
                var position = feature.getGeometry().getCoordinates()[0]
                popup.setPosition(position)
              }
            }
          })
          // 为map添加鼠标移动事件监听，当指向标注时改变鼠标光标状态
          _this.map.on('pointermove', function (e) {
            // console.log(e.originalEvent);
            var pixel = _this.map.getEventPixel(e.originalEvent)
            var hit = _this.map.hasFeatureAtPixel(pixel)
            _this.map.getTargetElement().style.cursor = hit ? 'pointer' : ''
          })
          drawLayer.setVisible(true)
        } else {
          // 切换显示图层, 关闭高亮显示图层
          // console.log('摄像头关闭状态');
          drawLayer.setVisible(false)
          // _this.map.removeLayer(drawLayer)
        }
      }
    },
  },
}
</script>

<style>
* {
  margin: 0;
  padding: 0;
}
#map_container {
  height: 660px;
  width: 100vw;
  position: relative;
}
/* 底图切换 */
.map_switch {
  position: fixed;
  width: 240px;
  height: 100px;
  bottom: 10px;
  right: 10px;
  z-index: 150;
}
.map_switch img {
  width: 100px;
  height: 100px;
  margin-right: 10px;
  cursor: pointer;
  border: 3px solid rgb(84 139 84);
}
/* 鼠标控件 */
#mouse-position {
  position: fixed;
  left: 0px;
  bottom: 25px;
  z-index: 2000;
  color: #ff2d51;
  width: 200px;
  height: 50px;
  background-color: rgba(174, 238, 238, 0.15);
  border-radius: 10px;
  text-align: center;
  line-height: 50px;
}
/* 放大缩小控件 */
.ol-zoom {
  top: 0.5em;
  right: 0.5em;
}
.ol-zoom-extent {
  top: 4.643em;
  right: 0.5em;
}
.ol-zoomslider {
  position: fixed;
  right: 0.5em;
  top: 10.2em;
  width: 35px;
  height: 200px;
}

/* 监控视频 */
.ol-popup {
  position: absolute;
  background-color: white;
  -webkit-filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2));
  filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2));
  padding: 9px;
  border-radius: 10px;
  border: 1px solid #cccccc;
  bottom: 45px;
  left: -50px;
}

.ol-popup:after,
.ol-popup:before {
  top: 100%;
  border: solid transparent;
  content: ' ';
  height: 0;
  width: 0;
  position: absolute;
  pointer-events: none;
}

.ol-popup:after {
  border-top-color: white;
  border-width: 10px;
  left: 48px;
  margin-left: -10px;
}

.ol-popup:before {
  border-top-color: #cccccc;
  border-width: 11px;
  left: 48px;
  margin-left: -11px;
}

.ol-popup-closer {
  text-decoration: none;
  position: absolute;
  top: 2px;
  right: 8px;
}

.ol-popup-closer:after {
  content: '✖';
}

#popup-content {
  font-size: 14px;
  font-family: '微软雅黑';
}
</style>
